<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>2. Using the Python Interpreter 使用 Python 解释器 &mdash; Python v2.7 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.7',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v2.7 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v2.7 documentation" href="../index.html" />
    <link rel="up" title="The Python Tutorial" href="index.html" />
    <link rel="next" title="3. An Informal Introduction to Python Python 概要介绍" href="introduction.html" />
    <link rel="prev" title="1. Whetting Your Appetite 开胃菜" href="appetite.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
 

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             accesskey="M">modules</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="3. An Informal Introduction to Python Python 概要介绍"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="appetite.html" title="1. Whetting Your Appetite 开胃菜"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.7 documentation</a> &raquo;</li>

          <li><a href="index.html" accesskey="U">The Python Tutorial</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="using-the-python-interpreter-python">
<span id="tut-using"></span><h1>2. Using the Python Interpreter 使用　Python 解释器<a class="headerlink" href="#using-the-python-interpreter-python" title="Permalink to this headline">¶</a></h1>
<div class="section" id="invoking-the-interpreter">
<span id="tut-invoking"></span><h2>2.1. Invoking the Interpreter 调用解释器<a class="headerlink" href="#invoking-the-interpreter" title="Permalink to this headline">¶</a></h2>
<p>The Python interpreter is usually installed as <tt class="docutils literal"><span class="pre">/usr/local/bin/python</span></tt> on
those machines where it is available; putting <tt class="docutils literal"><span class="pre">/usr/local/bin</span></tt> in your
Unix shell&#8217;s search path makes it possible to start it by typing the command</p>
<p>通常 Python 的解释器被安装在目标机器的 <tt class="docutils literal"><span class="pre">/usr/local/bin/python</span></tt> 目录下；
把 <tt class="docutils literal"><span class="pre">/usr/local/bin</span></tt> 目录放进你的 Unix Shell 的搜索路径里，确保它可以通过
输入</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">python</span>
</pre></div>
</div>
<p>to the shell.  Since the choice of the directory where the interpreter lives is
an installation option, other places are possible; check with your local Python
guru or system administrator.  (E.g., <tt class="docutils literal"><span class="pre">/usr/local/python</span></tt> is a popular
alternative location.)</p>
<p>来启动。因为安装路径是可选的，所以也有可能安装在其它位置，你可以与安装
Python 的用户或系统管理员联系。（例如， <tt class="docutils literal"><span class="pre">/usr/local/python</span></tt> 就是一个很常见
的选择）</p>
<p>On Windows machines, the Python installation is usually placed in
<tt class="docutils literal"><span class="pre">C:\Python27</span></tt>, though you can change this when you&#8217;re running the
installer.  To add this directory to your path,  you can type the following
command into the command prompt in a DOS box</p>
<p>在 Windows机器上，Python 通常安装在 <tt class="docutils literal"><span class="pre">C:\Python27</span></tt> 当然，我们在运行安装程序的
时候可以改变它。需要把这个目录加入到我们的 Path 中的话，可以像下面这样
在 DOS 窗中输入命令行</p>
<div class="highlight-python"><pre>set path=%path%;C:\\python27</pre>
</div>
<p>Typing an end-of-file character (<tt class="docutils literal"><span class="pre">Control-D</span></tt> on Unix, <tt class="docutils literal"><span class="pre">Control-Z</span></tt> on
Windows) at the primary prompt causes the interpreter to exit with a zero exit
status.  If that doesn&#8217;t work, you can exit the interpreter by typing the
following command: <tt class="docutils literal"><span class="pre">quit()</span></tt>.</p>
<p>输入一个文件结束符（Unix上是 <tt class="docutils literal"><span class="pre">Ctrl+D</span></tt> ，Windows上是 <tt class="docutils literal"><span class="pre">Ctrl+Z</span></tt>
）解释器会以 0 值退出。如果这没有起作用，你可以输入以下命令退出：
<tt class="docutils literal"><span class="pre">quit()</span></tt> 。</p>
<p>The interpreter&#8217;s line-editing features usually aren&#8217;t very sophisticated.  On
Unix, whoever installed the interpreter may have enabled support for the GNU
readline library, which adds more elaborate interactive editing and history
features. Perhaps the quickest check to see whether command line editing is
supported is typing Control-P to the first Python prompt you get.  If it beeps,
you have command line editing; see Appendix <a class="reference external" href="interactive.html#tut-interacting"><em>Interactive Input Editing and History Substitution</em></a> for an
introduction to the keys.  If nothing appears to happen, or if <tt class="docutils literal"><span class="pre">^P</span></tt> is echoed,
command line editing isn&#8217;t available; you&#8217;ll only be able to use backspace to
remove characters from the current line.</p>
<p>解释器的行编辑功能并不很复杂。装在 Unix 上的解释器可能会有 GNU readline
库支持，这样就可以额外得到精巧的交互编辑和历史记录功能。可能检查命令行
编辑器支持能力。最方便的方式是在主提示符下输入 Control-P。如果有嘟嘟声（计算
机扬声器），说明你可以使用命令行编辑功能，从附录 <a class="reference external" href="interactive.html#tut-interacting"><em>Interactive Input Editing and History Substitution</em></a> 可以查到快捷键的
介绍。如果什么声音也没有，或者显示 <tt class="docutils literal"><span class="pre">^p</span></tt> ，说明命令行编辑功能不可用，
你只有用退格键删掉输入的命令了。</p>
<p>The interpreter operates somewhat like the Unix shell: when called with standard
input connected to a tty device, it reads and executes commands interactively;
when called with a file name argument or with a file as standard input, it reads
and executes a <em>script</em> from that file.</p>
<p>解释器的操作有些像 Unix Shell：使用终端设备做为标准输入来调用它时，解
释器交互的解读和执行命令，通过文件名参数或以文件做为标准输入设备时，它
从文件中解读并执行 <em>脚本</em> 。</p>
<p>A second way of starting the interpreter is <tt class="docutils literal"><span class="pre">python</span> <span class="pre">-c</span> <span class="pre">command</span> <span class="pre">[arg]</span> <span class="pre">...</span></tt>,
which executes the statement(s) in <em>command</em>, analogous to the shell&#8217;s
<a class="reference external" href="../using/cmdline.html#cmdoption-c"><em class="xref">-c</em></a> option.  Since Python statements often contain spaces or other
characters that are special to the shell, it is usually advised to quote
<em>command</em> in its entirety with single quotes.</p>
<p>启动解释器的第二个方法是 <tt class="docutils literal"><span class="pre">python</span> <span class="pre">-c</span> <span class="pre">command</span> <span class="pre">[arg]</span> <span class="pre">...</span></tt> ，这种方法可以在
<em>命令行</em> 中直接执行语句，等同于Shell的 -c 选项。因为Python语句通常会包括
空格之类的特殊字符，所以最好把整个 <em>命令</em> 用单引号包起来。</p>
<p>Some Python modules are also useful as scripts.  These can be invoked using
<tt class="docutils literal"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">module</span> <span class="pre">[arg]</span> <span class="pre">...</span></tt>, which executes the source file for <em>module</em> as
if you had spelled out its full name on the command line.</p>
<p>有些 Python 模块也可以当作脚本使用。它们可以用
<tt class="docutils literal"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">module</span> <span class="pre">[arg]...</span></tt>
调用，这样就会像你在命令行中给出其完整名字一样运行 <em>模块</em> 源文件。</p>
<p>Note that there is a difference between <tt class="docutils literal"><span class="pre">python</span> <span class="pre">file</span></tt> and <tt class="docutils literal"><span class="pre">python</span> <span class="pre">&lt;file</span></tt>.
In the latter case, input requests from the program, such as calls to
<a title="input" class="reference external" href="../library/functions.html#input"><tt class="xref docutils literal"><span class="pre">input()</span></tt></a> and <a title="raw_input" class="reference external" href="../library/functions.html#raw_input"><tt class="xref docutils literal"><span class="pre">raw_input()</span></tt></a>, are satisfied from <em>file</em>.  Since this file
has already been read until the end by the parser before the program starts
executing, the program will encounter end-of-file immediately.  In the former
case (which is usually what you want) they are satisfied from whatever file or
device is connected to standard input of the Python interpreter.</p>
<p>注意 <tt class="docutils literal"><span class="pre">python</span> <span class="pre">file</span></tt> 和 <tt class="docutils literal"><span class="pre">python</span> <span class="pre">&lt;file</span></tt> 是有区别的。对于后一种情况，程序中类
似于调用 <a title="input" class="reference external" href="../library/functions.html#input"><tt class="xref docutils literal"><span class="pre">input()</span></tt></a> 和 <a title="raw_input" class="reference external" href="../library/functions.html#raw_input"><tt class="xref docutils literal"><span class="pre">raw_input()</span></tt></a> 这样的输入请求，来自于确定
的 <em>文件</em> 。因为在解析器开始执行之前，文件已经完全读入，所以程序指向文件尾。在前一种情况
（这通常是你需要的） 它们读取联接到 Python 解释器的标准输入，无关它们是文件还是其它设备。</p>
<p>When a script file is used, it is sometimes useful to be able to run the script
and enter interactive mode afterwards.  This can be done by passing <a class="reference external" href="../using/cmdline.html#cmdoption-i"><em class="xref">-i</em></a>
before the script.  (This does not work if the script is read from standard
input, for the same reason as explained in the previous paragraph.)</p>
<p>使用脚本文件时，经常会运行脚本然后进入交互模式。这也可以通过在脚本之前
加上 <a class="reference external" href="../using/cmdline.html#cmdoption-i"><em class="xref">-i</em></a> 参数来实现。（如果脚本来自标准输入，就不能这样运行，与前一段提到的原因一样。）</p>
<div class="section" id="argument-passing">
<span id="tut-argpassing"></span><h3>2.1.1. Argument Passing 参数传递<a class="headerlink" href="#argument-passing" title="Permalink to this headline">¶</a></h3>
<p>When known to the interpreter, the script name and additional arguments
thereafter are passed to the script in the variable <tt class="docutils literal"><span class="pre">sys.argv</span></tt>, which is a
list of strings.  Its length is at least one; when no script and no arguments
are given, <tt class="docutils literal"><span class="pre">sys.argv[0]</span></tt> is an empty string.  When the script name is given as
<tt class="docutils literal"><span class="pre">'-'</span></tt> (meaning  standard input), <tt class="docutils literal"><span class="pre">sys.argv[0]</span></tt> is set to <tt class="docutils literal"><span class="pre">'-'</span></tt>.  When
<a class="reference external" href="../using/cmdline.html#cmdoption-c"><em class="xref">-c</em></a> <em>command</em> is used, <tt class="docutils literal"><span class="pre">sys.argv[0]</span></tt> is set to <tt class="docutils literal"><span class="pre">'-c'</span></tt>.  When
<a class="reference external" href="../using/cmdline.html#cmdoption-m"><em class="xref">-m</em></a> <em>module</em> is used, <tt class="docutils literal"><span class="pre">sys.argv[0]</span></tt>  is set to the full name of the
located module.  Options found after  <a class="reference external" href="../using/cmdline.html#cmdoption-c"><em class="xref">-c</em></a> <em>command</em> or <a class="reference external" href="../using/cmdline.html#cmdoption-m"><em class="xref">-m</em></a>
<em>module</em> are not consumed  by the Python interpreter&#8217;s option processing but
left in <tt class="docutils literal"><span class="pre">sys.argv</span></tt> for  the command or module to handle.</p>
<p>调用解释器时，脚本名和附加参数传入一个名为 <tt class="docutils literal"><span class="pre">sys.argv</span></tt> 的字符串列表。没有
给定脚本和参数时，它至少也有一个元素： <tt class="docutils literal"><span class="pre">sys.argv[0]</span></tt> 此时为空字符串。脚本
名指定为 <tt class="docutils literal"><span class="pre">'-'</span></tt> （表示标准输入）时， <tt class="docutils literal"><span class="pre">sys.argv[0]</span></tt> 被设定为 <tt class="docutils literal"><span class="pre">'-'</span></tt>
，使用 <a class="reference external" href="../using/cmdline.html#cmdoption-c"><em class="xref">-c</em></a> 指令时， <tt class="docutils literal"><span class="pre">sys.argv[0]</span></tt> 被设定为 <tt class="docutils literal"><span class="pre">'-c'</span></tt> 。 使用
<a class="reference external" href="../using/cmdline.html#cmdoption-m"><em class="xref">-m</em></a> <em>module</em> 参数时， <tt class="docutils literal"><span class="pre">sys.agv[0]</span></tt> 被设定
为指定模块的全名。:option:<cite>-c</cite> <em>command</em> 或者 <a class="reference external" href="../using/cmdline.html#cmdoption-m"><em class="xref">-m</em></a> <em>module</em> 之
后的参数不会被 Python 解释器的选项处理机制所截获，而是留在
<tt class="docutils literal"><span class="pre">sys.argv</span></tt> 中，供脚本命令操作。</p>
</div>
<div class="section" id="interactive-mode">
<span id="tut-interactive"></span><h3>2.1.2. Interactive Mode 交互模式<a class="headerlink" href="#interactive-mode" title="Permalink to this headline">¶</a></h3>
<p>When commands are read from a tty, the interpreter is said to be in <em>interactive
mode</em>.  In this mode it prompts for the next command with the <em>primary prompt</em>,
usually three greater-than signs (<tt class="docutils literal"><span class="pre">&gt;&gt;&gt;</span></tt>); for continuation lines it prompts
with the <em>secondary prompt</em>, by default three dots (<tt class="docutils literal"><span class="pre">...</span></tt>). The interpreter
prints a welcome message stating its version number and a copyright notice
before printing the first prompt:</p>
<p>从 tty 读取命令时，我们称解释器工作于 <em>交互模式</em> 。这种模式下它根据
<em>主提示符</em>
来执行，主提示符通常标识为三个大于号（ <tt class="docutils literal"><span class="pre">&gt;&gt;&gt;</span></tt> ）；继续的部分被称为
<em>从属提示符</em> ，由三个点标识（ <a href="#id1"><span class="problematic" id="id2">``</span></a>... `` ）。在第一行之前，解释器打印欢迎信息、
版本号和授权提示</p>
<div class="highlight-python"><pre>python
Python 2.7 (#1, Feb 28 2010, 00:02:06)
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt;</pre>
</div>
<p>Continuation lines are needed when entering a multi-line construct. As an
example, take a look at this <a class="reference external" href="../reference/compound_stmts.html#if"><tt class="xref docutils literal"><span class="pre">if</span></tt></a> statement:</p>
<p>输入多行结构时需要从属提示符了，例如，下面这个 if 语句</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">the_world_is_flat</span> <span class="o">=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">if</span> <span class="n">the_world_is_flat</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="s">&quot;Be careful not to fall off!&quot;</span>
<span class="gp">...</span>
<span class="go">Be careful not to fall off!</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="the-interpreter-and-its-environment">
<span id="tut-interp"></span><h2>2.2. The Interpreter and Its Environment 解释器及其环境<a class="headerlink" href="#the-interpreter-and-its-environment" title="Permalink to this headline">¶</a></h2>
<div class="section" id="error-handling">
<span id="tut-error"></span><h3>2.2.1. Error Handling 错误处理<a class="headerlink" href="#error-handling" title="Permalink to this headline">¶</a></h3>
<p>When an error occurs, the interpreter prints an error message and a stack trace.
In interactive mode, it then returns to the primary prompt; when input came from
a file, it exits with a nonzero exit status after printing the stack trace.
(Exceptions handled by an <a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> clause in a <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> statement
are not errors in this context.)  Some errors are unconditionally fatal and
cause an exit with a nonzero exit; this applies to internal inconsistencies and
some cases of running out of memory.  All error messages are written to the
standard error stream; normal output from executed commands is written to
standard output.</p>
<p>有错误发生时，解释器打印一个错误信息和栈跟踪器。交互模式下，它返回主提
示符，如果从文件输入执行，它在打印栈跟踪器后以非零状态退出。（异常可以
由 <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> 语句中的 <a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> 子句来控制，这样就不会出现
上文中的错误信息）有一些非常致命的错误会导致非零状态下退出，这由通常由
内部矛盾和内存溢出造成。所有的错误信息都写入标准错误流；命令中执行的普
通输出写入标准输出。</p>
<p>Typing the interrupt character (usually Control-C or DEL) to the primary or
secondary prompt cancels the input and returns to the primary prompt. <a class="footnote-reference" href="#id5" id="id3">[1]</a>
Typing an interrupt while a command is executing raises the
<a title="exceptions.KeyboardInterrupt" class="reference external" href="../library/exceptions.html#exceptions.KeyboardInterrupt"><tt class="xref docutils literal"><span class="pre">KeyboardInterrupt</span></tt></a> exception, which may be handled by a <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a>
statement.</p>
<p>在主提示符或附属提示符输入中断符（通常是Control-C 或者 DEL）就会取消当
前输入，回到主命令行。 <a class="footnote-reference" href="#id6" id="id4">[2]</a> 2.2.执行命令时输入一个中断符会抛出一个
<a title="exceptions.KeyboardInterrupt" class="reference external" href="../library/exceptions.html#exceptions.KeyboardInterrupt"><tt class="xref docutils literal"><span class="pre">KeyboardInterrupt</span></tt></a> 异常，它可以被 <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> 句截获。</p>
</div>
<div class="section" id="executable-python-scripts-python">
<span id="tut-scripts"></span><h3>2.2.2. Executable Python Scripts 执行 Python 脚本<a class="headerlink" href="#executable-python-scripts-python" title="Permalink to this headline">¶</a></h3>
<p>On BSD&#8217;ish Unix systems, Python scripts can be made directly executable, like
shell scripts, by putting the line:</p>
<p>BSD类的 Unix系统中，Python 脚本可以像 Shell 脚本那样直接执行。只要在脚
本文件开头写一行命令，指定文件和模式</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c">#! /usr/bin/env python</span>
</pre></div>
</div>
<p>(assuming that the interpreter is on the user&#8217;s <span class="target" id="index-1457"></span><strong class="xref">PATH</strong>) at the beginning
of the script and giving the file an executable mode.  The <tt class="docutils literal"><span class="pre">#!</span></tt> must be the
first two characters of the file.  On some platforms, this first line must end
with a Unix-style line ending (<tt class="docutils literal"><span class="pre">'\n'</span></tt>), not a Windows (<tt class="docutils literal"><span class="pre">'\r\n'</span></tt>) line
ending.  Note that the hash, or pound, character, <tt class="docutils literal"><span class="pre">'#'</span></tt>, is used to start a
comment in Python.</p>
<p>(要确认 Python 解释器在用户的 <span class="target" id="index-1458"></span><strong class="xref">PATH</strong> 中) <tt class="docutils literal"><span class="pre">#!</span></tt> 必须是文件的前
两个字符，在某些平台上，第一行必须以 Unix 风格的行结束符（ <tt class="docutils literal"><span class="pre">'\n'</span></tt> ）结束，
不能用 Windows （ <tt class="docutils literal"><span class="pre">'\r\n'</span></tt> ） 的结束符。注意， <tt class="docutils literal"><span class="pre">'#'</span></tt> 是Python中是行
注释的起始符。</p>
<p>The script can be given an executable mode, or permission, using the
<strong>chmod</strong> command:</p>
<p>脚本可以通过 chmod 命令指定执行模式和权限</p>
<div class="highlight-python"><pre>$ chmod +x myscript.py</pre>
</div>
<p>On Windows systems, there is no notion of an &#8220;executable mode&#8221;.  The Python
installer automatically associates <tt class="docutils literal"><span class="pre">.py</span></tt> files with <tt class="docutils literal"><span class="pre">python.exe</span></tt> so that
a double-click on a Python file will run it as a script.  The extension can
also be <tt class="docutils literal"><span class="pre">.pyw</span></tt>, in that case, the console window that normally appears is
suppressed.</p>
<p>Windows 系统上没有“执行模式”。 Python 安装程序自动将 <tt class="docutils literal"><span class="pre">.py</span></tt> 文件关
联到 <tt class="docutils literal"><span class="pre">python.exe</span></tt> ，所以在 Python 文件图标上双击，它就会作为脚本执行。
同样 <tt class="docutils literal"><span class="pre">.pyw</span></tt> 也作了这样的关联，通常它执行时不会显示控制台窗口。</p>
</div>
<div class="section" id="source-code-encoding">
<h3>2.2.3. Source Code Encoding 源程序编码<a class="headerlink" href="#source-code-encoding" title="Permalink to this headline">¶</a></h3>
<p>It is possible to use encodings different than ASCII in Python source files. The
best way to do it is to put one more special comment line right after the <tt class="docutils literal"><span class="pre">#!</span></tt>
line to define the source file encoding:</p>
<p>Python 的源文件可以通过编码使用 ASCII 以外的字符集。最好的做法是在 #!
行后面用一个特殊的注释行来定义字符集</p>
<div class="highlight-python"><pre># -*- coding: encoding -*-</pre>
</div>
<p>With that declaration, all characters in the source file will be treated as
having the encoding <em>encoding</em>, and it will be possible to directly write
Unicode string literals in the selected encoding.  The list of possible
encodings can be found in the Python Library Reference, in the section on
<a title="Encode and decode data and streams." class="reference external" href="../library/codecs.html#module-codecs"><tt class="xref docutils literal"><span class="pre">codecs</span></tt></a>.</p>
<p>根据这个声明，Python 会尝试将文件中的字符编码转为 <em>encoding</em> 编码。并且，它
尽可能的将指定的编码直接写成 Unicode 文本。在 Python 库参考手册 中
<a title="Encode and decode data and streams." class="reference external" href="../library/codecs.html#module-codecs"><tt class="xref docutils literal"><span class="pre">codecs</span></tt></a> 部份可以找到可用的编码列表（推荐使用 utf-8 处理中文－－译者注）。</p>
<p>For example, to write Unicode literals including the Euro currency symbol, the
ISO-8859-15 encoding can be used, with the Euro symbol having the ordinal value
164.  This script will print the value 8364 (the Unicode codepoint corresponding
to the Euro symbol) and then exit:</p>
<p>例如，可以用 ISO-8859-15 编码可以用来编写包含欧元符号的 Unicode 文本，
其编码值为 164。这个脚本会输出 8364 （欧元符号的 Unicode 对应编码） 然后退出</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># -*- coding: iso-8859-15 -*-</span>

<span class="n">currency</span> <span class="o">=</span> <span class="s">u&quot;€&quot;</span>
<span class="k">print</span> <span class="nb">ord</span><span class="p">(</span><span class="n">currency</span><span class="p">)</span>
</pre></div>
</div>
<p>If your editor supports saving files as <tt class="docutils literal"><span class="pre">UTF-8</span></tt> with a UTF-8 <em>byte order mark</em>
(aka BOM), you can use that instead of an encoding declaration. IDLE supports
this capability if <tt class="docutils literal"><span class="pre">Options/General/Default</span> <span class="pre">Source</span> <span class="pre">Encoding/UTF-8</span></tt> is set.
Notice that this signature is not understood in older Python releases (2.2 and
earlier), and also not understood by the operating system for script files with
<tt class="docutils literal"><span class="pre">#!</span></tt> lines (only used on Unix systems).</p>
<p>如果你的文件编辑器可以将文件保存为 <tt class="docutils literal"><span class="pre">UTF-8</span></tt> 格式，并且可以保存 UTF-8
<em>字节序标记</em> （即 BOM - Byte Order Mark），你可以用这个来代替编码声明。IDLE可以通过设定
<tt class="docutils literal"><span class="pre">Options/General/Default</span> <span class="pre">Source</span> <span class="pre">Encoding/UTF-8</span></tt> 来支持它。需要注意的是旧
版 Python 不支持这个标记（Python 2.2或更早的版本），也同样不去理解由操
作系统调用脚本使用的 <tt class="docutils literal"><span class="pre">#!</span></tt> 行（仅限于 Unix系统）。</p>
<p>By using UTF-8 (either through the signature or an encoding declaration),
characters of most languages in the world can be used simultaneously in string
literals and comments.  Using non-ASCII characters in identifiers is not
supported. To display all these characters properly, your editor must recognize
that the file is UTF-8, and it must use a font that supports all the characters
in the file.</p>
<p>使用 UTF-8 内码（无论是用标记还是编码声明），我们可以在字符串和注释中
使用世界上的大部分语言。标识符中不能使用非 ASCII 字符集。为了正确显示
所有的字符，你一定要在编辑器中将文件保存为 UTF-8 格式，而且要使用支持
文件中所有字符的字体。</p>
</div>
<div class="section" id="the-interactive-startup-file">
<span id="tut-startup"></span><h3>2.2.4. The Interactive Startup File 交互式环境的启动文件<a class="headerlink" href="#the-interactive-startup-file" title="Permalink to this headline">¶</a></h3>
<p>When you use Python interactively, it is frequently handy to have some standard
commands executed every time the interpreter is started.  You can do this by
setting an environment variable named <span class="target" id="index-1459"></span><a class="reference external" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><strong class="xref">PYTHONSTARTUP</strong></a> to the name of a
file containing your start-up commands.  This is similar to the <tt class="docutils literal"><span class="pre">.profile</span></tt>
feature of the Unix shells.</p>
<p>使用 Python 解释器的时候，我们可能需要在每次解释器启动时执行一些命令。
你可以在一个文件中包含你想要执行的命令，设定一个名为 <span class="target" id="index-1460"></span><a class="reference external" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><strong class="xref">PYTHONSTARTUP</strong></a> 的
环境变量来指定这个文件。这类似于 Unix shell的 <tt class="docutils literal"><span class="pre">.profile</span></tt> 文件。</p>
<p>This file is only read in interactive sessions, not when Python reads commands
from a script, and not when <tt class="docutils literal"><span class="pre">/dev/tty</span></tt> is given as the explicit source of
commands (which otherwise behaves like an interactive session).  It is executed
in the same namespace where interactive commands are executed, so that objects
that it defines or imports can be used without qualification in the interactive
session. You can also change the prompts <tt class="docutils literal"><span class="pre">sys.ps1</span></tt> and <tt class="docutils literal"><span class="pre">sys.ps2</span></tt> in this
file.</p>
<p>这个文件在交互会话期是只读的，当 Python 从脚本中解读文件或以终端
<tt class="docutils literal"><span class="pre">/dev/tty</span></tt> 做为外部命令源时则不会如此（尽管它们的行为很像是处在交互会话
期。）它与解释器执行的命令处在同一个命名空间，所以由它定义或引用的一切
可以在解释器中不受限制的使用。你也可以在这个文件中改变 <tt class="docutils literal"><span class="pre">sys.ps1</span></tt> 和
<tt class="docutils literal"><span class="pre">sys.ps2</span></tt> 指令。</p>
<p>If you want to read an additional start-up file from the current directory, you
can program this in the global start-up file using code like <tt class="docutils literal"><span class="pre">if</span>
<span class="pre">os.path.isfile('.pythonrc.py'):</span> <span class="pre">execfile('.pythonrc.py')</span></tt>.  If you want to use
the startup file in a script, you must do this explicitly in the script</p>
<p>如果你想要在当前目录中执行附加的启动文件，可以在全局启动文件中加入类似
以下的代码：
<tt class="docutils literal"><span class="pre">if</span> <span class="pre">os.path.isfile('.pythonrc.py'):</span> <span class="pre">execfile('.pythonrc.py')</span></tt>
。如果你想要在某个脚本中使用启动文件，必须要在脚本中写入这样的语句</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">os</span>
<span class="n">filename</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#39;PYTHONSTARTUP&#39;</span><span class="p">)</span>
<span class="k">if</span> <span class="n">filename</span> <span class="ow">and</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">isfile</span><span class="p">(</span><span class="n">filename</span><span class="p">):</span>
    <span class="nb">execfile</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
</pre></div>
</div>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id5" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id3">[1]</a></td><td>A problem with the GNU Readline package may prevent</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id6" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id4">[2]</a></td><td>包的一个问题可能会造成它无法正常工作。</td></tr>
</tbody>
</table>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="../contents.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="#">2. Using the Python Interpreter 使用　Python 解释器</a><ul>
<li><a class="reference external" href="#invoking-the-interpreter">2.1. Invoking the Interpreter 调用解释器</a><ul>
<li><a class="reference external" href="#argument-passing">2.1.1. Argument Passing 参数传递</a></li>
<li><a class="reference external" href="#interactive-mode">2.1.2. Interactive Mode 交互模式</a></li>
</ul>
</li>
<li><a class="reference external" href="#the-interpreter-and-its-environment">2.2. The Interpreter and Its Environment 解释器及其环境</a><ul>
<li><a class="reference external" href="#error-handling">2.2.1. Error Handling 错误处理</a></li>
<li><a class="reference external" href="#executable-python-scripts-python">2.2.2. Executable Python Scripts 执行 Python 脚本</a></li>
<li><a class="reference external" href="#source-code-encoding">2.2.3. Source Code Encoding 源程序编码</a></li>
<li><a class="reference external" href="#the-interactive-startup-file">2.2.4. The Interactive Startup File 交互式环境的启动文件</a></li>
</ul>
</li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="appetite.html"
                                  title="previous chapter">1. Whetting Your Appetite 开胃菜</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="introduction.html"
                                  title="next chapter">3. An Informal Introduction to Python Python 概要介绍</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/tutorial/interpreter.txt"
         rel="nofollow">Show Source</a></li>
</ul>

          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="3. An Informal Introduction to Python Python 概要介绍"
             >next</a> |</li>
        <li class="right" >
          <a href="appetite.html" title="1. Whetting Your Appetite 开胃菜"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.7 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Tutorial</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2010, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.  
    <a href="http://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Oct 04, 2010.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.5.
    </div>

  </body>
</html>